<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>栈的应用（1） | 我爱着，我所热爱的人与事</title><meta name="keywords" content="数据结构"><meta name="author" content="Guocheng12"><meta name="copyright" content="Guocheng12"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="关于栈的一些应用：PS：介绍的应用是从大名鼎鼎黑皮书——马克·艾伦·维斯的《数据结构预算法分析》中摘选~ 1：平衡符号leetcode上面OJ：  https:&#x2F;&#x2F;leetcode-cn.com&#x2F;problems&#x2F;valid-parentheses&#x2F;submissions&#x2F;   思路： 既然要判断左右括号的匹配，那么每一个花括号，中括号，小括号等等，只要出现了左括号，那么就一定要匹配上其右括号。">
<meta property="og:type" content="article">
<meta property="og:title" content="栈的应用（1）">
<meta property="og:url" content="https://guocheng12.github.io/2021/03/11/%E6%A0%88%E7%9A%84%E5%BA%94%E7%94%A8%EF%BC%881%EF%BC%89/index.html">
<meta property="og:site_name" content="我爱着，我所热爱的人与事">
<meta property="og:description" content="关于栈的一些应用：PS：介绍的应用是从大名鼎鼎黑皮书——马克·艾伦·维斯的《数据结构预算法分析》中摘选~ 1：平衡符号leetcode上面OJ：  https:&#x2F;&#x2F;leetcode-cn.com&#x2F;problems&#x2F;valid-parentheses&#x2F;submissions&#x2F;   思路： 既然要判断左右括号的匹配，那么每一个花括号，中括号，小括号等等，只要出现了左括号，那么就一定要匹配上其右括号。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://riyugo.com/i/2021/03/12/5465v3.jpg">
<meta property="article:published_time" content="2021-03-11T07:00:47.000Z">
<meta property="article:modified_time" content="2021-03-11T19:22:16.551Z">
<meta property="article:author" content="Guocheng12">
<meta property="article:tag" content="数据结构">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://riyugo.com/i/2021/03/12/5465v3.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://guocheng12.github.io/2021/03/11/%E6%A0%88%E7%9A%84%E5%BA%94%E7%94%A8%EF%BC%881%EF%BC%89/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-03-12 03:22:16'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://riyugo.com/i/2021/03/12/3q37a5.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">3</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">1</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://riyugo.com/i/2021/03/12/5465v3.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">我爱着，我所热爱的人与事</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">栈的应用（1）</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-03-11T07:00:47.000Z" title="发表于 2021-03-11 15:00:47">2021-03-11</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-03-11T19:22:16.551Z" title="更新于 2021-03-12 03:22:16">2021-03-12</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="关于栈的一些应用："><a href="#关于栈的一些应用：" class="headerlink" title="关于栈的一些应用："></a><strong>关于栈的一些应用：</strong></h2><p>PS：介绍的应用是从大名鼎鼎黑皮书——马克·艾伦·维斯的《数据结构预算法分析》中摘选~</p>
<p>1：平衡符号<br>leetcode上面OJ：</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/valid-parentheses/submissions/">https://leetcode-cn.com/problems/valid-parentheses/submissions/</a></p>
</blockquote>
<p><img src="https://img-blog.csdnimg.cn/20210311133024478.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzUwOTg2MzQy,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<p><strong>思路：</strong></p>
<p>既然要判断左右括号的匹配，那么每一个花括号，中括号，小括号等等，只要出现了左括号，那么就一定要匹配上其右括号。</p>
<p>那么这样，想到了什么？“先进后出”貌似是最好的方法<br>定义一个栈，如果是 ’ ( ‘   ‘ [ ‘  ‘ { ‘ 等左边括号，那么就让它们统统入栈<br>当：遇到 ‘ ) ‘  ‘ ] ‘  ‘ } ‘ 等右括号，这个时候，让刚刚入栈的元素出栈</p>
<h2 id="1"><a href="#1" class="headerlink" title="1."></a>1.</h2><p><img src="https://img-blog.csdnimg.cn/20210311134828709.png" alt="在这里插入图片描述"></p>
<h2 id="2"><a href="#2" class="headerlink" title="2."></a>2.</h2><p>’ ( ‘   ‘ [ ‘  ‘ { ‘ 等左边括号，那么就让它们统统入栈<br><img src="https://img-blog.csdnimg.cn/20210311134840348.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzUwOTg2MzQy,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<h2 id="3"><a href="#3" class="headerlink" title="3."></a>3.</h2><p>遇到 ‘ ) ‘  ‘ ] ‘  ‘ } ‘ 等右括号：将刚刚入栈的元素取 栈顶（top）。<br>与字符串中s的元素进行比较后，不同就返回false，相同则，先出栈 （Pop）之后返回循环，继续遍历字符串s。</p>
<p><img src="https://img-blog.csdnimg.cn/20210311142453987.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzUwOTg2MzQy,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<p>注意点：（其实就是博主自己掉入坑。。）</p>
<p>首先先放上一张图：<br><img src="https://img-blog.csdnimg.cn/20210311142640186.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzUwOTg2MzQy,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>这是第一次提交的情况。这里有一点得注意到了，这里还要用到一个接口<br>StackEmpty（）；<br>用来判断栈当前是否已经为空了。（本人的接口返回：空返回1,非空返回0）</p>
<p>就按照刚刚我的思路，遍历字符串遇到了 ‘ [ ‘就入栈，然后呢？然后我的第一版程序就直接跳出循环了，返回true了。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">bool</span> <span class="title">isValid</span><span class="params">(<span class="keyword">char</span> * s)</span></span>&#123;</span><br><span class="line">    Stack st;</span><br><span class="line">    StackInit(&amp;st);</span><br><span class="line">    <span class="keyword">while</span>(*s != <span class="string">&#x27;\0&#x27;</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span>(*s == <span class="string">&#x27;[&#x27;</span> || *s == <span class="string">&#x27;(&#x27;</span> || *s == <span class="string">&#x27;&#123;&#x27;</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            StackPush(&amp;st,*s);</span><br><span class="line">            ++s;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">        &#123;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">char</span> top = StackTop(&amp;st);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span>(*s == <span class="string">&#x27;]&#x27;</span> &amp;&amp; top != <span class="string">&#x27;[&#x27;</span>)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">if</span>(*s == <span class="string">&#x27;)&#x27;</span> &amp;&amp; top != <span class="string">&#x27;(&#x27;</span>)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span>(*s == <span class="string">&#x27;&#125;&#x27;</span> &amp;&amp; top != <span class="string">&#x27;&#123;&#x27;</span>)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">            StackPop(&amp;st);</span><br><span class="line">            ++s;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    StackDestroy(&amp;st);</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br></pre></td></tr></table></figure>
<p>这里就会失败了。</p>
<p>正确的做法是我们应该思考到：如果StackEmpty返回为空了，那么意思就是栈里面的元素都已经出栈完了，也就是说：左括号已经全部匹配上了！</p>
<p>所以在下面我们得加一条语句</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> ret = StackEmpty(&amp;st);<span class="comment">//如果为空，则全部匹配上；非空则没有匹配上</span></span><br><span class="line"><span class="comment">//返回1 即 bool类型返回 ture</span></span><br><span class="line"><span class="comment">//返回0 即 bool类型返回 false</span></span><br><span class="line"><span class="keyword">return</span> ret;</span><br></pre></td></tr></table></figure>
<p>当然还有一点，要是遇到这种情况呢？<br><img src="https://img-blog.csdnimg.cn/20210311144802364.png" alt="在这里插入图片描述"><br>那么前面两个的确匹配到了，它们其中一个出栈，另一个遍历过去<br>就变成了这样：<br><img src="https://img-blog.csdnimg.cn/20210311145029687.png" alt="在这里插入图片描述"><br>这样的话，如果按照刚刚代码逻辑，第一版本的代码最终会报错<br>这里插播一下~ 断言真好用</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">assert(pst-&gt;_top &gt; <span class="number">0</span>);<span class="comment">//判断是否还能取到_top（栈顶）</span></span><br></pre></td></tr></table></figure>

<p>这个时候就报断言错误了，因为这个时候的栈顶已经被Pop出去了，啥都取不到了现在。</p>
<p>=w=加一句if判断即可~</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(StackEmpty(&amp;st));<span class="comment">//如果已经为空了，就不需要再遍历了，直接返回false就好</span></span><br><span class="line"><span class="keyword">return</span> <span class="literal">false</span>;</span><br></pre></td></tr></table></figure>

<h2 id="最终代码："><a href="#最终代码：" class="headerlink" title="最终代码："></a><em><strong>最终代码：</strong></em></h2><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="keyword">char</span> ElementType;</span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> <span class="title">Stack</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">	ElementType* _a;<span class="comment">//前_：表示成员</span></span><br><span class="line">	<span class="keyword">int</span> _top; <span class="comment">//栈顶下标</span></span><br><span class="line">	<span class="keyword">int</span> _capacity;</span><br><span class="line"></span><br><span class="line">&#125;Stack;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">StackInit</span><span class="params">(Stack* pst)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">StackDestroy</span><span class="params">(Stack* pst)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">StackPush</span><span class="params">(Stack* pst, ElementType x)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">StackPop</span><span class="params">(Stack* pst)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">StackSize</span><span class="params">(Stack* pst)</span></span>;</span><br><span class="line"><span class="comment">//返回1是空，返回0是非空</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">StackEmpty</span><span class="params">(Stack* pst)</span></span>;</span><br><span class="line"><span class="function">ElementType <span class="title">StackTop</span><span class="params">(Stack* pst)</span></span>;<span class="comment">//返回栈顶的下标</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">StackInit</span><span class="params">(Stack* pst)</span><span class="comment">// 初始化栈</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	assert(pst);</span><br><span class="line"></span><br><span class="line">	pst-&gt;_a = <span class="built_in">malloc</span>(<span class="keyword">sizeof</span>(ElementType)*<span class="number">4</span>);</span><br><span class="line">	pst-&gt;_top = <span class="number">0</span>;</span><br><span class="line">	pst-&gt;_capacity = <span class="number">4</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">StackDestroy</span><span class="params">(Stack* pst)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	assert(pst);</span><br><span class="line">	<span class="built_in">free</span>(pst-&gt;_a);</span><br><span class="line">	pst-&gt;_a = <span class="literal">NULL</span>;</span><br><span class="line">	pst-&gt;_top = pst-&gt;_capacity = <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">StackPush</span><span class="params">(Stack* pst, ElementType x)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	assert(pst);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (pst-&gt;_top == pst-&gt;_capacity)</span><br><span class="line">	&#123;</span><br><span class="line">		pst-&gt;_capacity *= <span class="number">2</span>;</span><br><span class="line">		ElementType* tmp = (ElementType*)<span class="built_in">realloc</span>(pst-&gt;_a, <span class="keyword">sizeof</span>(ElementType)*pst-&gt;_capacity);</span><br><span class="line">		<span class="keyword">if</span> (tmp == <span class="literal">NULL</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">&quot;Wrong!&quot;</span>);</span><br><span class="line">			<span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">		&#123;</span><br><span class="line">			pst-&gt;_a = tmp;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	pst-&gt;_a[pst-&gt;_top] = x;</span><br><span class="line">	pst-&gt;_top++;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">StackPop</span><span class="params">(Stack* pst)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	assert(pst);</span><br><span class="line">	assert(pst-&gt;_top &gt; <span class="number">0</span>);</span><br><span class="line">	--pst-&gt;_top;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">StackSize</span><span class="params">(Stack* pst)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	assert(pst);</span><br><span class="line">	<span class="keyword">return</span> pst-&gt;_top;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">StackEmpty</span><span class="params">(Stack* pst)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	assert(pst);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> pst-&gt;_top == <span class="number">0</span> ? <span class="number">1</span> : <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function">ElementType <span class="title">StackTop</span><span class="params">(Stack* pst)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	assert(pst);</span><br><span class="line">	assert(pst-&gt;_top &gt; <span class="number">0</span>);</span><br><span class="line">	<span class="keyword">return</span> pst-&gt;_a[pst-&gt;_top - <span class="number">1</span>];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">bool</span> <span class="title">isValid</span><span class="params">(<span class="keyword">char</span> * s)</span></span>&#123;</span><br><span class="line">    Stack st;</span><br><span class="line">    StackInit(&amp;st);</span><br><span class="line">    <span class="keyword">while</span>(*s != <span class="string">&#x27;\0&#x27;</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span>(*s == <span class="string">&#x27;[&#x27;</span> || *s == <span class="string">&#x27;(&#x27;</span> || *s == <span class="string">&#x27;&#123;&#x27;</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            StackPush(&amp;st,*s);</span><br><span class="line">            ++s;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">if</span>(StackEmpty(&amp;st))</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">char</span> top = StackTop(&amp;st);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span>(*s == <span class="string">&#x27;]&#x27;</span> &amp;&amp; top != <span class="string">&#x27;[&#x27;</span>)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">if</span>(*s == <span class="string">&#x27;)&#x27;</span> &amp;&amp; top != <span class="string">&#x27;(&#x27;</span>)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span>(*s == <span class="string">&#x27;&#125;&#x27;</span> &amp;&amp; top != <span class="string">&#x27;&#123;&#x27;</span>)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">            StackPop(&amp;st);</span><br><span class="line">            ++s;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> ret = StackEmpty(&amp;st);</span><br><span class="line">    StackDestroy(&amp;st);</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="https://img-blog.csdnimg.cn/20210311145714570.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzUwOTg2MzQy,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>搞定啦，接下来我还会更新一些栈的应用的！欢迎大家一起来找我讨论讨论，交流交流哈~</p>
<p>很喜欢用一个up主口中的“去学习了”  ————那就是“去打天下啦”！<br>下期见</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">GuoCheng12</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://guocheng12.github.io/2021/03/11/%E6%A0%88%E7%9A%84%E5%BA%94%E7%94%A8%EF%BC%881%EF%BC%89/">https://guocheng12.github.io/2021/03/11/%E6%A0%88%E7%9A%84%E5%BA%94%E7%94%A8%EF%BC%881%EF%BC%89/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">此文章版權歸作者GuoCheng12所有，如有轉載，請註明來自原作者</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/">数据结构</a></div><div class="post_share"><div class="social-share" data-image="https://riyugo.com/i/2021/03/12/5465v3.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="next-post pull-full"><a href="/2021/03/09/%E6%A0%88/"><img class="next-cover" src="https://riyugo.com/i/2021/03/12/55u2k2.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">数据结构 ---- 栈</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2021/03/09/栈/" title="数据结构 ---- 栈"><img class="cover" src="https://riyugo.com/i/2021/03/12/55u2k2.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-09</div><div class="title">数据结构 ---- 栈</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%B3%E4%BA%8E%E6%A0%88%E7%9A%84%E4%B8%80%E4%BA%9B%E5%BA%94%E7%94%A8%EF%BC%9A"><span class="toc-number">1.</span> <span class="toc-text">关于栈的一些应用：</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1"><span class="toc-number">2.</span> <span class="toc-text">1.</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2"><span class="toc-number">3.</span> <span class="toc-text">2.</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3"><span class="toc-number">4.</span> <span class="toc-text">3.</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9C%80%E7%BB%88%E4%BB%A3%E7%A0%81%EF%BC%9A"><span class="toc-number">5.</span> <span class="toc-text">最终代码：</span></a></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By Guocheng12</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">欢迎来到我的博客~</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>